package com.ming.common.beetl.init;

import com.ming.common.beetl.cache.CacheSqlExecUtil;
import com.ming.common.beetl.cache.CacheSqlManagerUtil;
import com.ming.common.beetl.entity.*;
import com.ming.common.beetl.enums.DictEnums;
import com.ming.common.beetl.util.DataSourceUtil;
import com.ming.common.beetl.util.SQLManagerUtil;
import com.ming.common.beetl.util.SqlUtil;
import com.ming.common.beetl.util.StrUtil;
import com.zaxxer.hikari.HikariDataSource;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.query.LambdaQuery;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Component

public class MdaoInit {

    @Resource
    private SQLManager sqlManager;

    @PostConstruct
    public void init(){
        initSQLManagerAll();
        //initSQLExecAll();
    }

    public void initSQLExecAll(){
//        String tableName = DictEnums.TableInfo.ivy_db_sql_exec.value();
//        String primaryKey = DictEnums.TableInfo.ivy_db_sql_exec.label();
//        List<? extends BaseEntity> list = SQLManagerUtil.NEW().sqlManager(sqlManager).tableName(tableName).primaryKey(primaryKey).selectAll();

        List<IvyDbSql> list = sqlManager.lambdaQuery(IvyDbSql.class).select();
        list.forEach(m->{
            //String sqlId = m.getStrValue(StrUtil.snakeToCamel("sql_id"));
            String sqlId = m.getSqlId();
            CacheSqlExecUtil.NEW().key(sqlId).put(c -> m);
        });
    }

    public void initSQLManagerAll(){
        String tableName = DictEnums.TableInfo.ivy_db_sql_manager.value();
        String primaryKey = DictEnums.TableInfo.ivy_db_sql_manager.label();

        /*DictEnums.TableInfo ivy_db_datasource = DictEnums.TableInfo.ivy_db_datasource;
        Map<Long, ? extends BaseEntity> dataSourceMap = SQLManagerUtil.NEW()
                .sqlManager(sqlManager)
                .tableName(ivy_db_datasource.value())
                .primaryKey(ivy_db_datasource.label())
                .selectAllToLongMap(m -> m.getLongValue("id"), Function.identity());*/

        Map<Long, IvyDbDatasource> dataSourceMap = sqlManager.lambdaQuery(IvyDbDatasource.class).select().stream().collect(Collectors.toMap(IvyDbDatasource::getId, m->m));

        //List<? extends BaseEntity> list = SQLManagerUtil.NEW().sqlManager(sqlManager).tableName(tableName).primaryKey(primaryKey).selectAll();
        List<IvyDbSqlManager> list = sqlManager.lambdaQuery(IvyDbSqlManager.class).select();
        list.forEach(m->{
//            Long id = m.getLongValue("id");
//            String dbStyle = m.getStrValue("dbStyle");
//            String type = m.getStrValue("type");
//            String smBeanName = m.getStrValue("smBeanName");
//            Long datasourceId = m.getLongValue("datasourceId");
//            String slaveDatasourceIds = m.getStrValue("slaveDatasourceIds");
            Long id = m.getId();
            String dbStyle = m.getDbStyle();
            String type = m.getType();
            String smBeanName = m.getSmBeanName();
            Long datasourceId = m.getDatasourceId();
            String slaveDatasourceIds = m.getSlaveDatasourceIds();

            String[] slaveArr = null;
            if(!"single".equalsIgnoreCase(type) && cn.hutool.core.util.StrUtil.isNotBlank(slaveDatasourceIds)){
                slaveArr = slaveDatasourceIds.split(",");
            }
            IvyDbDatasource ivyDbDatasource = dataSourceMap.get(datasourceId);
            //构建主数据源
            HikariDataSource hikariDataSource = DataSourceUtil.NEW().ivyDbDatasource(ivyDbDatasource).build();

            //构建从数据源
            List<DataSource> slaveDataSourceList = null;
            DataSource[] slaveDataSources = null;
            if(slaveArr != null){
                slaveDataSourceList = new ArrayList<>();
                for (String slaveId : slaveArr){
                    IvyDbDatasource slaveDbDatasource = dataSourceMap.get(Long.parseLong(slaveId));
                    HikariDataSource slaveDataSource = DataSourceUtil.NEW().ivyDbDatasource(slaveDbDatasource).build();
                    slaveDataSourceList.add(slaveDataSource);
                }
                slaveDataSources = slaveDataSourceList.toArray(new DataSource[0]);
            }

            //构建beetlsql管理器
            SQLManagerEntity entity = new SQLManagerEntity();
            entity.setDataSource(hikariDataSource);
            entity.setSlaveDataSources(slaveDataSources);
            entity.setDbStyle(DictEnums.DbStyle.getDbStyle(dbStyle));
            entity.setInitSql(null);
            //entity.setBaseEntity(m);
            entity.setIvyDbSqlManager(m);
            SQLManager buildSQLManager = SqlUtil.buildSQLManager(entity);

            //缓存beetlsql管理器
            CacheSqlManagerUtil.NEW().key(smBeanName).put(c -> buildSQLManager);
            CacheSqlManagerUtil.NEW().key(id).put(c -> buildSQLManager);
            //CacheSqlManagerUtil2.NEW().key(id).put(c -> buildSQLManager);
            /*Cache<String, SQLManager> cacheList = CacheSqlManagerUtil.getCacheList();
            SQLManager cache = CacheSqlManagerUtil.getCache(smBeanName, SQLManager.class);
            cache.execute(new SQLReady("select * from dev_job"),Map.class);*/
            //System.out.println();
        });
    }

}
